/**
 * <p>文件名:		MessageServiceJMSImpl.java</p>
 * <p>版权:		CopyrightTag</p>
 * <p>公司:		千方集团CTFO</p>
 * @author		周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 */

package com.caits.lbs.framework.services.sms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.activemq.command.ActiveMQDestination;
import org.apache.log4j.Logger;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.util.Assert;

import com.caits.lbs.framework.log.CommonLogFactory;
import com.caits.lbs.framework.utils.TimeUtils;

/**
 * <p>
 * MessageServiceJMSImpl
 * </p>
 * <p>
 * 用途：短消息发送的jms实现
 * </p>
 * 
 * @author 周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version 0.0.1 2012-10-17
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>zhb</td>
 *          <td>2012-10-17 下午5:31:11</td>
 *          </tr>
 *          <tr>
 *          <td>0.0.1</td>
 *          <td>创建类</td>
 *          <td>zhb</td>
 *          <td>2012-10-17 下午5:31:11</td>
 *          <td>0.0.2</td>
 *          <td>修改类</td>
 *          <td>xxx</td>
 *          <td>x年x月x日</td>
 *          </tr>
 *          </table>
 */
public class MessageServiceJMSImpl extends Thread implements IMessageService {

	/** 日志记录器 */
	private Logger log = CommonLogFactory.getLog();

	/** 真正的消息发送对象 */
	private JmsTemplate jmsSender;

	/** 接收消息的身份 */
	private ActiveMQDestination receiveDest;

	/** 接收消息超时时间ms */
	private long receiveTimeout=30*1000;

	/** 消息消费者列表 */
	private final List<IConsumeMessage> consumeList = Collections.synchronizedList(new ArrayList<IConsumeMessage>());

	/** 接收线程是否运行 */
	private boolean bRun = false;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.caits.lbs.framework.services.sms.IMessageService#sendMessage(com.
	 * caits.lbs.framework.services.sms.IMessage)
	 */
	@Override
	public void sendMessage(final IMessage msg) {
		try {
			Assert.notNull(jmsSender, "消息发送对象jmsTemplate不能为空.");
			Assert.notNull(msg, "消息内容msg不能为空.");
			jmsSender.send(new MessageCreator() {
				public Message createMessage(Session session) throws JMSException {
					Message mm = session.createMessage();
					mm.setLongProperty("DATADATE", TimeUtils.truncatTimeFromDate(System.currentTimeMillis()));
					mm.setStringProperty(msg.getHead(), msg.getBody());
					return mm;
				}
			});
			log.info("消息已发送," + msg.getHead() + ":" + msg.getBody() + ",DEST:" + jmsSender.getDefaultDestination());
		} catch (Exception e) {
			log.error("消息发送失败,msg=" + msg.getBody(), e);
		}
	}

	/**
	 * 开始接收消息 
	 */
	public void startListen() {
		bRun=true;
		start();
	}

	/**
	 * 停止接收消息 
	 */
	public void stopListen() {
		bRun=false;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		while (bRun ) {
			try {
				jmsSender.setReceiveTimeout(receiveTimeout);
				Message msg = jmsSender.receive(receiveDest);
				if (msg != null) {
					log.info("收到消息:" + receiveDest.getPhysicalName());
					dispatchMessage(msg);
				}else{
					log.debug("没有收到消息,"+receiveTimeout+"ms内.");
				}
			} catch (JmsException e) {
				log.error("接收消息失败.", e);
			}
		}
		log.info("接收消息线程结束.");
	}

	/* (non-Javadoc)
	 * @see com.caits.lbs.framework.services.sms.IMessageService#registerConsumer(com.caits.lbs.framework.services.sms.IConsumeMessage)
	 */
	@Override
	public void registerConsumer(IConsumeMessage consumer) {
		if(!consumeList.contains(consumer))
			consumeList.add(consumer);
	}

	/**
	 * 给消费者列表分配消息 
	 * @param message
	 */
	public void dispatchMessage(Object message) {
		for(IConsumeMessage consumer:consumeList){
			try{
				if(consumer!=null)consumer.onMessage(message);
			}catch(Exception e){
				log.error("消费者处理消息异常,consume="+consumer.hashCode(), e);
			}
		}
	}

	/**
	 * 获取变量<code>jmsSender</code>的值
	 * 
	 * @return 返回的数据类型是<code>JmsTemplate</code>
	 */
	public JmsTemplate getJmsSender() {
		return jmsSender;
	}

	/**
	 * 设置变量<code> jmsSender</code> 的值
	 * 
	 * @param jmsSender
	 *            <code>jmsSender</code> 参数类型是<code>JmsTemplate</code>
	 */
	public void setJmsSender(JmsTemplate jmsSender) {
		this.jmsSender = jmsSender;
	}

	/**
	 * 获取变量<code>receiveTimeout</code>的值
	 * @return 返回的数据类型是<code>long</code>
	 */
	public long getReceiveTimeout() {
		return receiveTimeout;
	}

	/**
	 * 设置变量<code> receiveTimeout</code> 的值
	 * @param receiveTimeout  <code>receiveTimeout</code> 参数类型是<code>long</code>
	 */
	public void setReceiveTimeout(long receiveTimeout) {
		this.receiveTimeout = receiveTimeout;
	}

	/**
	 * 获取变量<code>receiveDest</code>的值
	 * @return 返回的数据类型是<code>ActiveMQDestination</code>
	 */
	public ActiveMQDestination getReceiveDest() {
		return receiveDest;
	}

	/**
	 * 设置变量<code> receiveDest</code> 的值
	 * @param receiveDest  <code>receiveDest</code> 参数类型是<code>ActiveMQDestination</code>
	 */
	public void setReceiveDest(ActiveMQDestination receiveDest) {
		this.receiveDest = receiveDest;
	}

}
